<template>
  <div class="news-activity-detail g-padding-x">
		<div class="news-activity-detail-nav">
      <a :href="`${hostPath}/activity`">精彩活动</a>
		  <div class="text-[#9C9DB4] ellipsis flex-1 ml-[4px]"> / {{ detail?.title }}</div>
    </div>
    <div class="news-activity-detail-header h-[330px] pb-[32px] flex-wrap mt-[24px]">
      <img :src="detail?.coverImg" :alt="detail?.title" class="w-[530px] h-[330px]" />
      <div class="news-activity-detail-header-left flex-1">
        <div>
          <StatusTag :activityType="detail?.activityType" class="mr-[8px]" /> 
          <span class="news-activity-detail-header-left-title flex-1">{{ detail?.title }}</span>
          <div class="mt-[16px] text-[var(--devui-placeholder)]">
            <GIcon
              name="gt-line-date"
              class="mr-[8px]"
              color="var(--devui-placeholder)"
            />
            <span
              >活动时间： {{ detail?.startTime }} 至
              {{ detail?.endTime }}</span
            >
          </div>
          <div
            class="news-activity-detail-header-left-status mt-[16px]"
            :class="{
              'text-[var(--tag-text-blue-color)]': detail?.status === 1,
            }"
            :style="{
              background: statusList[detail?.status || 0].bgColor,
            }"
          >
            {{ statusList[detail?.status || 0].text }}
          </div>
        </div>
        <GLink class="mt-[32px]" :to="detail?.extLink" v-if="detail?.extLink">
          <d-button variant="solid" color="primary"> {{ detail?.actionText || '点击查看' }}</d-button>
        </GLink>
      </div>
    </div>
		<div class="news-activity-detail-title">
			{{ detail?.title }}
		</div>
		<div class="mt-[24px]">
			<div class="dp-editor-md-preview-container dp-md-view overflow-auto" v-html="htmlString" @click="handleClick" />
		</div>
  </div>
</template>
<script lang="ts" setup>
import md from "@/utils/md";
import activityData from '@/pages/Data/activity.json'
import { metaConverter } from '@/utils/index';
import { useNuxtApp, useAsyncData } from '#app'
import { useClipboard } from '@vueuse/core'
import { Message } from 'vue-devui/message'
import StatusTag from '../components/StatusTag.vue'

const hostPath = (import.meta as any).env.VITE_HOST
const { copy } = useClipboard()
const detail = ref({})
const activityStatus = ref(0)
const htmlString = ref('')
const activityPath = ref('')
const serverDes = ref('')
const statusList = [{
  text: '活动未开始',
  bgColor: '#fff',
}, {
  text: '活动进行中',
  bgColor: '#DBE2FA',
}, {
  text: '活动已结束',
  bgColor: '#F1F1F8',
}]

const nuxtApp = useNuxtApp()
const router = useRouter();
// 查找文章的内容
async function getArticle() {
  detail.value = activityData.find(item => item.id === router.currentRoute.value?.params.id);

	const currentTime = new Date();
  const startTimes = new Date(detail.value?.startTime);
  const endTimes = new Date(detail.value?.endTime);
	detail.value['status'] = currentTime < startTimes ? 0 : currentTime > endTimes ? 2 : 1;

	activityPath.value = detail.value?.path || ''
	const res = await useAsyncData('fileContent', () => nuxtApp.$readFile(activityPath.value))
	const html = md.render(metaConverter(res?.data.value || ''));
  htmlString.value = handleHtmlString(html);

  // 获取描述
  const noTagData = html.replace(/<[^>]*>/g, '')
  const descContent = noTagData.split('\n').filter(item => item)
  serverDes.value = descContent.join().substring(0, 200);
}
getArticle();
// 添加复制按钮
const codeCopyIcon = `<svg class="icon md-view-copy-icon" aria-hidden="true" style="font-size:16px;display: inline-block;color:#3B3E55;"><use xlink:href="#gt-line-copy"></use></svg>`;
function handleHtmlString(html: string) {
  try {
    const regex =
      /<pre([^>]*)>([\s\S]*?)<code([^>]*)>([\s\S]*?)<\/code>([\s\S]*?)<\/pre>/g;
    return html.replace(
      regex,
      (
        match,
        preAttributes,
        preContent,
        codeAttributes,
        codeContent
        // postContent,
      ) => {
        // 在匹配的标签后面插入复制按钮，并保留样式
        return `<pre ${preAttributes}>${preContent}<code ${codeAttributes}>${codeContent}</code>${codeCopyIcon}</pre>`;
      }
    );
  } catch {
    return html;
  }
}

// 复制 详情中的代码
function handleClick(event: any) {
    const isCopyIcon = event.target.classList.contains('md-view-copy-icon')
    if (isCopyIcon) {
        let text = event.target?.previousElementSibling?.textContent || ''
        if (text.slice(-1) === '\n') {
            text = text.substring(0, text.length - 1)
        }
        copy(text)
        Message.success('复制成功')
    }
}

useSeoMeta({
  charset: 'utf-8',
  title: () => `${detail.value?.title} - GitCode资讯中心`,
  ogTitle: () => `${detail.value?.title} - GitCode资讯中心`,
  description: () => serverDes.value,
  ogDescription: () => serverDes.value,
  keywords: () => detail.value?.keywords || '',
  ogKeywords: () => detail.value?.keywords || '',
})
</script>
<style lang="scss">
@import '~/assets/css/devui_mdpreview.scss';
.news-activity-detail {
	color: #3B3E55;
  max-width: 1200px;
  margin: auto;
  margin-top: 32px;
	&-nav {
		font-size: 16px;
		color: #242536;
    display: flex;
    align-items: center;
	}
	&-header {
		display: flex;
		img {
			border-radius: 4px;
      object-fit: contain;
		}
		&-left {
			margin-left: 32px;
			display: flex;
      flex-direction: column;
			justify-content: center;
			&-title {
				font-size: 20px;
				font-weight: 600;
				color: #000;
			}
			&-status {
        width: fit-content;
        border: 1px solid #E3E3EE;
        border-radius: 100px;
        padding: 1px 8px;
      }
		}
	}
	&-title {
		font-size: 24px;
		font-weight: 600;
		color: #242536;
		margin-top: 24px;
		text-align: center;
	}
	.dp-md-view {
		pre {
			position: relative;
      code {
        padding-right: 32px !important;
      }
		}
		.md-view-copy-icon {
			cursor: pointer;
			position: absolute;
			right: 8px;
			top: 9px;
			&:hover {
				opacity: 0.5;
			}
		}
	}
}
@media screen and (max-width: 768px) {
	.news-activity-detail-header {
		height: 100%;
		padding-bottom: 0;
		img {
			width: 100%;
			height: auto;
		}
		&-left {
			margin-left: 0px;
			margin-top: 16px;
			flex-direction: row;
			justify-content: space-between;
			flex-wrap: wrap;
		}
	}
  .news-activity-detail {
    margin-top: 16px;
  }
}
</style>